from django.forms import fields, Form, widgets
from app01.forms.bootstrapform import BootStrapForm
from django.core.exceptions import ValidationError
from app01.forms import widgets as wid
from app01 import models

class ProjectForm(BootStrapForm, Form):
    bootstrap_class_exclude = ['color']
    name = fields.CharField(label='项目名')
    color_choices = [
        (1, '#56b8eb'),
        (2, '#f28033'),
        (3, '#ebc656'),
        (4, '#a2d148'),
        (5, '#20bfa4'),
        (6, '#7461c2'),
        (7, '#20bfa3'),
    ]
    color = fields.CharField(label='颜色', widget=wid.ColorRadioSelect(choices=color_choices))
    desc = fields.CharField(label='描述', widget=widgets.Textarea)

    def __init__(self, request, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.request = request

    def clean_name(self):
        name = self.cleaned_data.get('name')
        exists = models.Project.objects.filter(name=name, creator=self.request.tracer.user).exists()
        if exists:
            raise ValidationError('项目名已存在')
        count = models.Project.objects.filter(creator=self.request.tracer.user).count()
        if count >= self.request.tracer.price_policy.project_num:
            raise ValidationError('项目个数超限,请购买套餐')
        return name
